package cn.glow.readingcloud.account.service.impl;


import cn.glow.readingcloud.account.dao.UserLikeSeeMapper;
import cn.glow.readingcloud.account.service.UserLikeSeeService;
import cn.glow.readingcloud.book.feign.client.BookClient;
import cn.glow.readingcloud.common.pojo.Book;
import cn.glow.readingcloud.common.pojo.BriefBook;
import cn.glow.readingcloud.common.pojo.UserLikeSee;
import cn.glow.readingcloud.common.result.Result;
import cn.glow.readingcloud.common.result.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Glow
 * @Date 2023-04-16 20:57:28
 * @Description 用户喜好功能接口实现服务层
 * @Version 1.0
 */
@Service
public class UserLikeSeeServiceImpl extends ServiceImpl<UserLikeSeeMapper, UserLikeSee> implements UserLikeSeeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLikeSeeServiceImpl.class);

    @Autowired
   private UserLikeSeeMapper userLikeSeeMapper;
   @Autowired
   private RedisTemplate redisTemplate;
   @Autowired
   private BookClient bookClient;
    @Override
    public Result likeSeeClick(Integer userId, String bookId, Integer value) {
       try {
           if(value == 0)
           {
               LambdaQueryWrapper<UserLikeSee> queryWrapper = new LambdaQueryWrapper<>();
               queryWrapper.eq(UserLikeSee::getUserId,userId);
               queryWrapper.eq(UserLikeSee::getBookId,bookId);
               userLikeSeeMapper.delete(queryWrapper);

           }
           else if(value == 1)
           {
               UserLikeSee userLikeSee = new UserLikeSee();
               userLikeSee.setBookId(bookId);
               userLikeSee.setUserId(userId);
               userLikeSeeMapper.insert(userLikeSee);
           }
           //缓存更新
           redisTemplate.opsForHash().put("UserId:"+userId+"LikeBook",bookId,value);
       }catch (Exception e)
       {
           LOGGER.error("槽作异常：请重试，原因如下:{}",e);
           return ResultUtil.fail();
       }

        return ResultUtil.success().buildMessage("添加成功！");
    }

    @Override
    public Result<Long> getBookLikesCount(String bookId) {
        Long count = (Long) redisTemplate.opsForValue().get("BookLikeID:"+bookId);
        if(count == null)
        {
            LambdaQueryWrapper<UserLikeSee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserLikeSee::getBookId, bookId);
            count = userLikeSeeMapper.selectCount(queryWrapper);
            redisTemplate.opsForValue().set("BookLikeID:"+bookId,count,20, TimeUnit.MINUTES);
        }
        return ResultUtil.success(count);
    }

    @Override
    public Result getUserLikeBookList(Integer userId, Integer page, Integer limit) {
        try {
            Page<UserLikeSee> pages = new Page<>(page, limit);
            LambdaQueryWrapper<UserLikeSee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserLikeSee::getUserId, userId);
            List<UserLikeSee> list = userLikeSeeMapper.selectPage(pages, queryWrapper).getRecords();
            List<BriefBook> briefBookList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                BriefBook briefBook = new BriefBook();
                BeanUtils.copyProperties(list.get(i), briefBook);
                Book book = bookClient.getBookById(briefBook.getBookId()).getData();
                //因为book实体的属性可以完全复制到book简单信息，不用一个一个set.
                BeanUtils.copyProperties(book, briefBook);
                briefBookList.add(briefBook);

            } return ResultUtil.success(briefBookList);
        }catch (Exception e)
        {
            LOGGER.error("获取用户[{}]喜欢书单异常：{}", userId, e);
            return ResultUtil.fail();
        }

    }

    @Override
    public Result userLikeThisBook(Integer userId, String bookId) {
        LambdaQueryWrapper<UserLikeSee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLikeSee::getUserId,userId);
        queryWrapper.eq(UserLikeSee::getBookId,bookId);
        UserLikeSee userLikeSee = userLikeSeeMapper.selectOne(queryWrapper);
        if (userLikeSee == null)
        {
            return ResultUtil.notFound(0);
        }
        return ResultUtil.success(1);
    }
}
